﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.NetworkInformation;
using MiruPublic;

namespace MangaKurosagi
{
    public partial class ReadChap : PhoneApplicationPage
    {
        Popup popup = new Popup();

        private bool UnLockRotation = false;

        public ReadChap()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string PinStart;

            NavigationContext.QueryString.TryGetValue("Pinstart", out PinStart);

            if (PinStart == "true")
            {
                string TitleChap;
                string Url;
                NavigationContext.QueryString.TryGetValue("TitleChap", out TitleChap);
                NavigationContext.QueryString.TryGetValue("Url", out Url);
                Global.ChapSelected = new Chap() { Title = TitleChap, Url = Url, Update = true };

                string RootTitle;
                string RootUrl;
                //string Description;
                //string UrlImage;
                NavigationContext.QueryString.TryGetValue("RootTitle", out RootTitle);
                //NavigationContext.QueryString.TryGetValue("Description", out Description);
                NavigationContext.QueryString.TryGetValue("RootUrl", out RootUrl);
               // NavigationContext.QueryString.TryGetValue("UrlImage", out UrlImage);
                Global.StoriesSelected = new Stories() { Title = RootTitle, Url = RootUrl };
            }

            if (Global.ChapSelected.Update == true)
            {
                Global.ChapSelected.Update = false;

                ReadClient_Load();
            }
        }

        private void ReadClient_Load()
        {
            ControlManager.ShowLoading(popup, "Đang tải nội dung truyện vui lòng chờ! \nNhấn vào màn hình để bỏ qua màn hình chờ", true);

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Không thể kết nối mạng \n Kiểm tra wifi/cellular và truy cập lại để tải truyện");

                popup.IsOpen = false;

                return;
            }

            Global.ChapSelected.GetHtmlContent();

            Global.ChapSelected.GetContentCompleted += (s, args) =>
            {
                ReadClient.NavigateToString(args.Content);
            };
        }

        private void ReadClient_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            popup.IsOpen = false;
        }

        private void BtnLockRotation_Click(object sender, EventArgs e)
        {
            if (UnLockRotation)
            {
                SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
            }
            else
            {
                switch (Orientation)
                {
                    case PageOrientation.None:
                    case PageOrientation.Portrait:
                    case PageOrientation.PortraitUp:
                    case PageOrientation.PortraitDown:
                        SupportedOrientations = SupportedPageOrientation.Portrait;
                        break;
                    case PageOrientation.Landscape:
                    case PageOrientation.LandscapeLeft:
                    case PageOrientation.LandscapeRight:
                        SupportedOrientations = SupportedPageOrientation.Landscape;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
            UnLockRotation = !UnLockRotation;
        }

        private void BtnPin_Click(object sender, EventArgs e)
        {
            var newTile = new StandardTileData()
            {
                Title = Global.ChapSelected.Title,
                BackContent = Global.StoriesSelected.Title,
                BackgroundImage = new Uri("/Background.png", UriKind.RelativeOrAbsolute),
                BackBackgroundImage = new Uri(Global.StoriesSelected.UrlImage, UriKind.Absolute),
                //new Uri("/Background.png", UriKind.RelativeOrAbsolute),
                // Count = 42,

            };
            string navigate = "";
            navigate += "TitleChap=" + Global.ChapSelected.Title;
            navigate += "&Pinstart=true";
            navigate += "&Url=" + HttpUtility.UrlEncode(Global.ChapSelected.Url);
            navigate += "&RootTitle=" + Global.StoriesSelected.Title;
            navigate += "&RootUrl=" + HttpUtility.UrlEncode(Global.StoriesSelected.Url);

            ShellTile.Create(new Uri("/ReadChap.xaml?" + navigate, UriKind.Relative), newTile);
        }

        private void BtnHome_Click(object sender, EventArgs e)
        {
            popup.IsOpen = false;

            NavigationService.Navigate(new Uri("/ViewDetails.xaml?", UriKind.Relative));
        }

        private void SaveIstorage_Click(object sender, EventArgs e)
        {
            SaveUnfinishChap();
        }

        private void BtnPreview_Click(object sender, EventArgs e)
        {
            popup.IsOpen = false;

            Global.StoriesSelected.GetListChap();

            Global.StoriesSelected.GetListChapCompleted += (s, args) =>
            {
                if (Global.ChapSelected.index + 1 < args.listResult.Count)
                {
                    var chapPreviewer = args.listResult.Where(chap => chap.index == Global.ChapSelected.index + 1);

                    if (chapPreviewer.Count() > 0)
                    {
                        ItemChap item = chapPreviewer.First();

                        if (item != null)
                        {
                            Global.ChapSelected = new Chap() { Url = item.Url, Title = item.Title, Update = true, index = item.index };

                            ReadClient_Load();
                        }
                    }
                }
            };            
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            popup.IsOpen = false;

            Global.StoriesSelected.GetListChap();

            Global.StoriesSelected.GetListChapCompleted += (s, args) =>
            {
                if (Global.ChapSelected.index - 1 >= 0)
                {
                    var chapPreviewer = args.listResult.Where(chap => chap.index == Global.ChapSelected.index - 1);

                    if (chapPreviewer.Count() > 0)
                    {
                        ItemChap item = chapPreviewer.First();

                        if (item != null)
                        {
                            Global.ChapSelected = new Chap() { Url = item.Url, Title = item.Title, Update = true, index = item.index };

                            ReadClient_Load();
                        }
                    }
                }
            };    
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var Result = MessageBox.Show("Có thể bạn chưa đọc xong tập này.\nBạn muốn lưu lại lần sau đọc tiếp hay không?","Lưu lại đang đọc",MessageBoxButton.OKCancel);

            popup.IsOpen = false;

            if (Result == MessageBoxResult.OK)
            {
                SaveUnfinishChap();
            }
        }

        private void SaveUnfinishChap()
        {
            if (Global.ListChapUnFinish.Where(s => s.Title == Global.ChapSelected.Title).Count() <= 0)
            {
                ChapUnfinish chap = new ChapUnfinish();
                chap.Title = Global.ChapSelected.Title;
                chap.index = Global.ChapSelected.index;
                chap.Url = Global.ChapSelected.Url;
                chap.Update = true;
                chap.root = Global.StoriesSelected;
                Global.ListChapUnFinish.Add(chap);
                StorageHelper.SaveUnfinishXML("ChapUnfinish.xml", Global.ListChapUnFinish);
            }
        }
    }
}